# Qt
from PySide2.QtWidgets import QApplication, QMainWindow, QDialog,QFileDialog,QColorDialog
from PySide2.QtGui import QIcon
from PySide2.QtCore import QObject,Signal,Qt,QTime
from ui.mainWindow import Ui_MainWindow
# qtui.py
# 从文件中加载UI定义
from PySide2.QtWidgets import QButtonGroup
# python
import json,os,datetime,time,threading,traceback,webbrowser,sys
from pygoogletranslation import Translator
# mypython
from libs.mypthon.oss_info import ossinfo
    # 宏定义
    #核心操作
from libs.mypthon import textToAss, makeVideo, DEFINE, audioToText, mytranslate, tool, ossutil


#定义信号类，子线程发送信号，主线程处理ui
class mySignal(QObject):
    #文本信息
    ui_textInfo=Signal(str,str,str)
    #进度条
    ui_processPar=Signal(float,float)
    ui_progressPar=Signal(float)
    #开始按钮
    ui_pushButton_startMakeVideo=Signal(bool)
    #工具:翻译完成
    tool_trans_over=Signal(str)


# 定义主窗口类
# 注意 这里选择的父类 要和你UI文件窗体一样的类型
class mainWindow(QMainWindow):
# 构造函数
    def __init__(self):
        super().__init__()
        # 导入ui界面类
        self.ui = Ui_MainWindow()
        # 为主窗口 初始化,设置 ui界面
        self.ui.setupUi(self)
        #图标
        appIcon = QIcon("../jingting_datas/图标.png")
        self.setWindowIcon(appIcon)
        # ui
            #进度条
        self.ui.progressBar_process.hide()
        self.ui.progressBar_progress.hide()
            #单选框
        self.group=QButtonGroup(self)
        self.group.addButton(self.ui.radioButton_makeVideo_usePicWidHei)
        self.group.addButton(self.ui.radioButton_makeVideo_useComWidHei)
        self.group.addButton(self.ui.radioButton_makeVideo_useComWid)
        self.group.addButton(self.ui.radioButton_makeVideo_useComHei)

        # 调用到的函数
        self.call_function()

#重要函数=>
    # 构造函数中 调用到的函数 都放在此处
    def call_function(self):
        # 定义成员变量(放在最前面)
        self.def_member_variable()
        # 加载设置数据到UI上
        self.loadSettingToUi()
        # 链接 信号和曹
        self.link_signal_slot()
        #
        self.create_file_path()

    # 定义成员变量
    def def_member_variable(self):
        # 阿里用户信息类对象
        self.idinfo = None
        # 音频列表
        self.audioFilelist = []
        #字幕文件转换列表
        self.swapSubtitList=[]
        # 宏定义
        # 展示信息到UI哪个部件
        self.DEF_ui_showToProcess = 'Process'
        self.DEF_ui_showToProgress = 'Progress'
        # 制作视频的背景图
        self.makeVideo_BacImg = ''
        #保存视频的路径,名字
        self.saveVideoPath=''
        self.saveVideoName=''
        #子线程发送信号
        self.mainWindowSignal=mySignal()
        #添加选项字幕链接音频列表
        self.addOptionSubtit_linklist=[]
        #通用选项字幕列表
        self.optionSubtitList=[]
        #水印
        self.addTextLogo_linklist=[]

    # 加载设置数据到UI上
    def loadSettingToUi(self):
        #默认保存视频的目录
        path=os.path.abspath(DEFINE.DEF_saveVideo_PATH)
        self.ui.lineEdit_saveVideoPath.setText(path)
        self.saveVideoPath=path
        # 加载阿里云oss,语音识别的配置 到UI上
        self.show_idInfo()

    # 链接 信号和曹
    def link_signal_slot(self):
        self.ui.pushButton_oss_info_ok.clicked.connect(self.save_idInfo)
        # 选择音频文件
        self.ui.pushButton_choiceAudioFiles.clicked.connect(self.chioceAudioFiles)
        # 点击 选择背景图
        self.ui.pushButton_makeVideo_chioceBacImg.clicked.connect(self.chioceBacImg)
        # 点击 开始制作视频
        self.ui.pushButton_startMakeVideo.clicked.connect(self.startMakeVideo)
        # 视频保存路径文本改变
        self.ui.lineEdit_saveVideoPath.textChanged.connect(self.slot_saveVideoPathTextChange)
        # 选择视频保存路径
        self.ui.pushButton_saveVideoPath.clicked.connect(self.slot_chioceSaveVideoPath)
        #子线程发送信号,主线程处理ui
        self.mainWindowSignal.ui_textInfo.connect(self.showInfoToUi)
        self.mainWindowSignal.ui_processPar.connect(self.show_processPar)
        self.mainWindowSignal.ui_progressPar.connect(self.show_progressPar)
        self.mainWindowSignal.ui_pushButton_startMakeVideo.connect(self.enable_pushButton_startMakeVideo)
        self.mainWindowSignal.tool_trans_over.connect(self.slot_trans_over)
        #点击打开保存路径
        self.ui.action_file_openSaveVideoPath.triggered.connect(self.slot_clickFile_openSaveVideoPath)
        #点击打开保存字幕的目录路径
        self.ui.action_file_openSaveAssfilePath.triggered.connect(lambda :os.startfile(os.path.abspath(
            DEFINE.DEF_ASSFILE_PATH)))
        #点击打开word文件目录
        self.ui.action_file_openWordfilePath.triggered.connect(lambda :os.startfile(os.path.abspath(
            DEFINE.DEF_WORDFILE_PATH)))
        #点击帮助
        self.ui.action_help_look_moreLan.triggered.connect(self.slot_clickHelp_look_look_moreLan)
        self.ui.action_help_look_subtitSytle.triggered.connect(self.slot_clickHelp_look_subtitSytle)
        self.ui.action_help_look_eng46OptionSubtit.triggered.connect(self.slot_action_help_look_eng46OptionSubtit)
        #清除程序输出信息
        self.ui.pushButton_clearUiTextOutInfo.clicked.connect(self.slot_pushButton_clearUiTextOutInfo)
        #选择颜色
        self.ui.pushButton_choiceSubtitColor.clicked.connect(self.slot_pushButton_choiceSubtitColor)
        self.ui.pushButton_choiceVideoBackImgColor.clicked.connect(self.slot_pushButton_choiceVideoBackImgColor)
        #选项字幕音频链接
        self.ui.pushButton_addOptionSubtit_linkAudio.clicked.connect(self.slot_pushButton_addOptionSubtit_linkAudio)
        self.ui.pushButton_addOptionSubtit_linkAudio_clearall.clicked.connect(self.slot_pushButton_addOptionSubtit_linkAudio_clearall)
        #添加水印音频链接
        self.ui.pushButton_addTextLogo_linkAudio.clicked.connect(self.slot_pushButton_addTextLogo_linkAudio)
        self.ui.pushButton_addTextLogo_linkAudio_clearall.clicked.connect(self.slot_pushButton_addTextLogo_linkAudio_clearall)
        #通用选项字幕
        self.ui.pushButton_optionSubtit_add.clicked.connect(self.slot_pushButton_optionSubtit_add)
        self.ui.pushButton_optionSubtit_clear.clicked.connect(self.slot_pushButton_optionSubtit_clear)
        self.ui.pushButton_optionSubtit_trans.clicked.connect(self.slot_pushButton_optionSubtit_trans)
        self.ui.pushButton_optionSubtit_swapTime.clicked.connect(self.slot_pushButton_optionSubtit_swapTime)
        #打开链接
        self.ui.commandLinkButton_setAliyunVideoHelp.clicked.connect(lambda :webbrowser.open('https://www.yuque.com/viggo-t7cdi/videosrt/em4n10',new=0,autoraise=True))
        self.ui.commandLinkButton_myblibli.clicked.connect(lambda :webbrowser.open('https://space.bilibili.com/500047662',0,True))
        self.ui.commandLinkButton_myCSDN.clicked.connect(lambda :webbrowser.open('https://blog.csdn.net/qq_62595450',0,True))
        self.ui.commandLinkButton_mygitee.clicked.connect(lambda :webbrowser.open('https://gitee.com/tmaofu',0,True))
        #添加appkey数据
        self.ui.pushButton_appkey_add.clicked.connect(self.slot_addAppKey)
        self.ui.pushButton_appkey_lookAll.clicked.connect(self.slot_showAppKey)
        self.ui.pushButton_appkey_del.clicked.connect(self.slot_delAppKey)
        #工具 字幕转换
        self.ui.pushButton_tool_swapSubtit_choice.clicked.connect(self.slot_pushButton_tool_swapSubtit_choice)
        self.ui.pushButton_tool_swapSubtit_start.clicked.connect(self.slot_pushButton_tool_swapSubtit_start)
        #工具 翻译
        self.ui.pushButton_tool_trans_satrt.clicked.connect(self.slot_pushButton_tool_trans_satrt)
        self.ui.plainTextEdit_tool_trans_oriText.textChanged.connect(self.slot_trans_showTextLen)

    #初始化需要的文件 路径
    def create_file_path(self):
        if not os.path.exists(DEFINE.DEF_ASSFILE_PATH):
            os.makedirs(DEFINE.DEF_ASSFILE_PATH)
        if not os.path.exists(DEFINE.DEF_WORDFILE_PATH):
            os.makedirs(DEFINE.DEF_WORDFILE_PATH)
        if not os.path.exists(DEFINE.DEF_saveVideo_PATH):
            os.makedirs(DEFINE.DEF_saveVideo_PATH)
        if not os.path.exists(DEFINE.DEF_temp_data_PATH):
            os.makedirs(DEFINE.DEF_temp_data_PATH)


#重要函数<=

#普通函数=>
    # 展现用户账号信息
    def show_idInfo(self):
        try:
            with open(DEFINE.DEF_IDINFO_PATH, 'r', encoding='utf-8') as rfile:
                text=rfile.read()
                if len(text)!=0:
                    info_dict = dict(eval(text))
                    # 文件不为空
                    if info_dict:
                        # 初始化成员变量
                        info = ossinfo(info_dict[DEFINE.KEY_AccessKeyId], info_dict[DEFINE.KEY_AccessKeySecret],
                                       info_dict[DEFINE.KEY_Endpoint], info_dict[DEFINE.KEY_BucketName],
                                       info_dict[DEFINE.KEY_AppKey])
                        self.idinfo = info
                if self.idinfo != None:
                    # 在UI上显示
                    self.ui.lineEdit_AccessKeyId.setText(self.idinfo.id)
                    self.ui.lineEdit_AccessKeySecret.setText(self.idinfo.secret)
                    self.ui.lineEdit_Endpoint.setText(self.idinfo.endpoint)
                    self.ui.lineEdit_BucketName.setText(self.idinfo.bucketname)
                    #appkey
                    appkeylist=self.idinfo.appKeylist
                    self.ui.comboBox_chioce_appkey.clear()
                    for i_dict in appkeylist:
                        self.ui.comboBox_chioce_appkey.addItem(str(i_dict))
        except:
            msg=traceback.format_exc()
            self.ui.plainTextEdit_processInfo.setPlainText('错误!{}'.format(msg))
            print('{}'.format(msg))

    #帮助发送信号
    def emitSignal_progressPar(self,process):
        self.mainWindowSignal.ui_progressPar.emit(process)
    def emitSignal_processPar(self,value,total):
        self.mainWindowSignal.ui_processPar.emit(value,total)
    # 语音识别用到:audioToText.fileTrans
    def emitSignal_TextInfo(self, flag, headstr, bodystr):
        # 是在子线程中用到,所以是发送信号
        self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProcess, headstr, bodystr)
    #开始制作视频按钮关闭,开启
    def emitSignal_startMakeVideo(self,bo):
        self.mainWindowSignal.ui_pushButton_startMakeVideo.emit(bo)

    #获取颜色
    def getColor(self):
        color=QColorDialog.getColor(initial=Qt.white,parent=self,title='选择颜色')
        if color.isValid()==False:
            # self.showInfoToUi(self.DEF_ui_showToProcess,'选择颜色','你未进行操作')
            return False,color
        else:
            return True,color


#普通函数<=

# 定义自己的槽函数
    # 视频保存路径文本改变
    def slot_saveVideoPathTextChange(self,text):
        self.saveVideoPath=text
        print('def slot_saveVideoPathTextChange(self,text):'.format(text))

    #选择视频保存路径
    def slot_chioceSaveVideoPath(self):
        dir=QFileDialog.getExistingDirectory(self,'选择保存视频的文件夹','')
        if len(dir) == 0:
            self.showInfoToUi(self.DEF_ui_showToProcess, '注意:', '你未选择文件,不进行操作')
        else:
            self.ui.lineEdit_saveVideoPath.setText(dir)
            self.saveVideoPath=dir

    # 保存用户oss账号信息
    def save_idInfo(self):
        try:
            with open(DEFINE.DEF_IDINFO_PATH, 'r', encoding='utf-8') as rfile:
                text=rfile.read()
                if len(text)!=0:
                    appkeylist=eval(text)[DEFINE.KEY_AppKey]
                else:
                    appkeylist=[]
            save_dict = {
                DEFINE.KEY_AccessKeyId: self.ui.lineEdit_AccessKeyId.text(),
                DEFINE.KEY_AccessKeySecret: self.ui.lineEdit_AccessKeySecret.text(),
                DEFINE.KEY_Endpoint: self.ui.lineEdit_Endpoint.text(),
                DEFINE.KEY_BucketName: self.ui.lineEdit_BucketName.text(),
                DEFINE.KEY_AppKey:appkeylist
            }
            str = json.dumps(save_dict)
            with open(DEFINE.DEF_IDINFO_PATH, 'w', encoding='utf-8') as wfile:
                wfile.write(str)
        # 提示
        except:
            msg=traceback.format_exc()
            print(msg)
            self.show_info('保存失败{}'.format(msg))
        else:
            self.show_info('保存成功')

    # 信息提示窗口
    def show_info(self, info):
        dialog = QDialog(parent=self)
        dialog.setWindowTitle('信息提示:{}'.format(info))
        dialog.setMinimumWidth(300)
        dialog.setMinimumHeight(100)
        dialog.show()

    #点击 选择音频文件
    def chioceAudioFiles(self):
        fileslist,suffix=QFileDialog.getOpenFileNames(self,'选择制作视频的音频文件','','*')
        if len(fileslist) == 0:
            self.showInfoToUi(self.DEF_ui_showToProcess, '注意:', '你未选择文件,不进行操作')
        else:
            self.audioFilelist=fileslist
            self.showInfoToUi(self.DEF_ui_showToProcess, '已经导入音频文件:', fileslist)

    # 点击 选择背景图
    def chioceBacImg(self):
        #('F:/test.jpg', '*')
        file,suffix = QFileDialog.getOpenFileName(self, '选择制作视频的背景图片', '', '*')
        if len(file) == 0:
            self.showInfoToUi(self.DEF_ui_showToProcess, '注意:', '你未选择文件,不进行操作')
        else:
            self.makeVideo_BacImg = file
            self.showInfoToUi(self.DEF_ui_showToProcess, '已经导入背景图片:', file)

    #展示信息到 ui 界面
    #文本框
    def showInfoToUi(self, chi_ui='', head='', arg=''):
        '''
        chi_ui='',磨人信息展示在progress
        :param chi_ui:str(self.DEF_ui_showToProcess
        :param head:str
        :param arg: str,list
        :return:
        '''
        if (type(arg)) ==type(list()):
            string=''
            for item in arg:
                if str(type(item)) =="<class 'bytes'>":
                    string=string+str(item,'utf-8')+'\n\n'
                else:
                    string = string + str(item) + '\n\n'
            if chi_ui==self.DEF_ui_showToProcess:
                self.ui.plainTextEdit_processInfo.appendPlainText(head+'\n'+string+'\n'+'{:*^30}'.format(''))
            elif chi_ui in [self.DEF_ui_showToProgress,'']:
                self.ui.plainTextEdit_progressInfo.appendPlainText(head + '\n' + string+'\n'+'{:*^30}'.format(''))
        else:
            # str(type(arg)) == "<class 'str'>":
            if str(type(arg)) == "<class 'bytes'>":
                arg_str=str(arg,'utf-8')
            else:
                arg_str=str(arg)
            if chi_ui==self.DEF_ui_showToProcess:
                self.ui.plainTextEdit_processInfo.appendPlainText(head+'\n'+arg_str+'\n'+'{:*^30}'.format(''))
            elif chi_ui in [self.DEF_ui_showToProgress, '']:
                self.ui.plainTextEdit_progressInfo.appendPlainText(head + '\n' + arg_str+'\n'+'{:*^30}'.format(''))
        #进度条
        #进度条

    #进度条
    def show_processPar(self,consumed,total):
        self.ui.progressBar_process.show()
        process=(consumed/total)*100
        self.ui.progressBar_process.setValue(process)
        if process==100:
            self.ui.progressBar_process.hide()

    def show_progressPar(self,process):
        self.ui.progressBar_progress.show()
        value=process*100
        # print('value======',value)
        self.ui.progressBar_progress.setValue(value)
        if process==1:
            self.ui.progressBar_progress.hide()

    def enable_pushButton_startMakeVideo(self,bo):
        if bo:
            self.ui.pushButton_startMakeVideo.setEnabled(True)
        else:
            self.ui.pushButton_startMakeVideo.setEnabled(False)

    #点击帮助
    def slot_clickHelp_look_subtitSytle(self):
        with open('../jingting_datas/字幕参数说明.txt','r',encoding='utf-8') as rfile:
            text=rfile.read()
            self.showInfoToUi(self.DEF_ui_showToProcess,'字幕参数说明',text)

    def slot_clickHelp_look_look_moreLan(self):
        with open('../jingting_datas/google_trans_info.json','r',encoding='utf-8') as rfile:
            text=rfile.read()
            self.showInfoToUi(self.DEF_ui_showToProcess,'更多翻译语言简写',text)

    def slot_action_help_look_eng46OptionSubtit(self):
        with open('../jingting_datas/四六级选项实例输入.txt','r',encoding='utf-8') as rfile:
            text=rfile.read()
            self.showInfoToUi(self.DEF_ui_showToProcess,'英语四六级听力选项示例',text)

    #点击文件
    def slot_clickFile_openSaveVideoPath(self):
        if len(self.saveVideoPath)==0:
            self.showInfoToUi(self.DEF_ui_showToProcess,'','保存视频文件的路径为空')
            return
        os.startfile(self.saveVideoPath)
    #点击清除信息
    def slot_pushButton_clearUiTextOutInfo(self):
        self.ui.plainTextEdit_processInfo.clear()
        self.ui.plainTextEdit_progressInfo.clear()

    #点击选择颜色
    def slot_pushButton_choiceVideoBackImgColor(self):
        is_success,color=self.getColor()
        if is_success:
            string=color.name()
            self.ui.lineEdit_makeVideo_pureColour.setText(string)
        else:
            self.showInfoToUi(self.DEF_ui_showToProcess,'选择背景颜色','你未进行操作')

    def slot_pushButton_choiceSubtitColor(self):
        is_success,color=self.getColor()
        if is_success:
            string=color.name()
            self.ui.lineEdit_subtit_primaryColour.setText(string)
        else:
            self.showInfoToUi(self.DEF_ui_showToProcess,'选择字幕颜色','你未进行操作')

    #通用选项字幕 添加
    def slot_pushButton_optionSubtit_add(self):
        begintime=self.ui.dateTimeEdit_optionSubtit_beginTime.time().toString('HH:mm:ss.00')
        endtime=self.ui.dateTimeEdit_optionSubtit_endTime.time().toString('HH:mm:ss.00')
        # print(begintime)
        # print(endtime)
        text=self.ui.plainTextEdit_optionSubtit_text.toPlainText()
        if len(text)==0 :
            self.show_info('文本内容为空')
            return
        dic={DEFINE.KEY_BENGINTIME:begintime, DEFINE.KEY_ENDTIME:endtime, DEFINE.KEY_TEXT:text}
        self.optionSubtitList.append(dic)
        #显示
        self.showInfoToUi(self.DEF_ui_showToProcess,'通用选项字幕-已添加:',self.optionSubtitList)
        #清空ui
        # self.ui.plainTextEdit_optionSubtit_text.clear()

    #通用选项字幕 清空
    def slot_pushButton_optionSubtit_clear(self):
        self.optionSubtitList.clear()
        self.showInfoToUi(self.DEF_ui_showToProcess, '通用选项字幕-已清空:', self.optionSubtitList)

    #通用选项字幕 一键翻译
    def slot_pushButton_optionSubtit_trans(self):
        tex=self.ui.plainTextEdit_optionSubtit_text.toPlainText()
        if self.ui.checkBox_subtitTrans_manLangue.isChecked():
            des=self.ui.lineEdit_subtitTrans_manLangueText.text()
        else:
            des=self.ui.comboBox_subtitTrans_langue.currentText()
        try:
            tr=Translator()
            t=tr.translate(tex,dest=des)
            tran_text=t.text
            self.ui.plainTextEdit_optionSubtit_text.appendPlainText('\n'+tran_text)
        except Exception:
            msg=traceback.format_exc()
            print(msg)
            self.showInfoToUi(self.DEF_ui_showToProcess,'错误:','翻译失败:{}'.format(msg))

    #通用选项字幕 交换时间
    def slot_pushButton_optionSubtit_swapTime(self):
        begintime = self.ui.dateTimeEdit_optionSubtit_beginTime.time()
        endtime = self.ui.dateTimeEdit_optionSubtit_endTime.time()
        # print(endtime)
        endtime=QTime(endtime).addSecs(1)
        self.ui.dateTimeEdit_optionSubtit_beginTime.setTime(endtime)
        self.ui.dateTimeEdit_optionSubtit_endTime.setTime(begintime)

    #点击绑定选项字幕到音频
    def slot_pushButton_addOptionSubtit_linkAudio(self):
        #通用选项字幕与四六级选项字幕不可同时添加
        engs46=self.ui.plainTextEdit_addOptionSubtit.toPlainText()
        opsubli=[]#十分重要
        opsubli=self.optionSubtitList
        if len(engs46)!=0 and len(opsubli)!=0:
            self.show_info('通用选项字幕与四六级选项字幕不可同时添加,请清除其中一个')
            return
        elif len(engs46)!=0 and len(opsubli)==0:
            model= DEFINE.DEF_addOptionSubtit_eng46_model
            load=engs46
        elif len(engs46)==0 and len(opsubli)!=0:
            model = DEFINE.DEF_addOptionSubtit_general_model
            load = list(opsubli)
        else:
            self.show_info('选项内容为空')
            return

        filename,suffix=QFileDialog.getOpenFileName(self,'选择绑定的音频文件','','*')
        if len(filename)==0:
            self.showInfoToUi(self.DEF_ui_showToProcess,'选择绑定的音频文件','你未进行操作')
            return

        #字幕风格
        if self.ui.checkBox_subtit_bold_2.isChecked():
            Bold = -1
        else:
            Bold = 0
        if self.ui.checkBox_subtit_italic_2.isChecked():
            Italic = -1
        else:
            Italic = 0
        if self.ui.checkBox_subtit_underline_2.isChecked():
            Underline = -1
        else:
            Underline = 0
        if self.ui.checkBox_subtit_spacing_2.isChecked():
            Spacing = self.ui.spinBox_subtit_spacing.value()
        else:
            Spacing = ''
        # 十六进制颜色(#FFFFFF
        # 字幕颜色(例如，&H00FFFFFF。&H+00+BBGGRR
        color = self.ui.lineEdit_subtit_primaryColour_2.text()
        newcolol = color.replace('#', '')
        font_color = '&H00' + newcolol[4:7] + newcolol[2:4] + newcolol[0:2]
        sytle_dict={DEFINE.KEY_assStyle_Fontname:self.ui.fontComboBox_subtit_font_2.currentText(),
                    DEFINE.KEY_assStyle_Fontsize:self.ui.spinBox_subtit_fontSize_2.value(),
                    DEFINE.KEY_assStyle_PrimaryColour:font_color,
                    DEFINE.KEY_assStyle_Bold:Bold,
                    DEFINE.KEY_assStyle_Italic:Italic,
                    DEFINE.KEY_assStyle_Underline:Underline,
                    DEFINE.KEY_assStyle_Spacing:Spacing,
                    DEFINE.KEY_assStyle_Alignment:self.ui.spinBox_subtit_alignment_2.value()}
        #链接信息
        i_dict={DEFINE.KEY_addOptionSubtit_text:load,
                DEFINE.KEY_addOptionSubtit_sytle:sytle_dict,
                DEFINE.KEY_addOptionSubtit_linkaudio:filename,
                DEFINE.KEY_addOptionSubtit_model:model
                }
        self.addOptionSubtit_linklist.append(i_dict)
        self.showInfoToUi(self.DEF_ui_showToProcess,'视频添加选项字幕,已经添加:','{}'.format(self.addOptionSubtit_linklist))
        #清空
        self.slot_pushButton_optionSubtit_clear()
        self.ui.plainTextEdit_addOptionSubtit.clear()

    #清空已经添加的选项信息
    def slot_pushButton_addOptionSubtit_linkAudio_clearall(self):
        self.addOptionSubtit_linklist.clear()
        self.showInfoToUi(self.DEF_ui_showToProcess,'视频添加选项字幕,已经清空','')

    #添加水印
    def slot_pushButton_addTextLogo_linkAudio(self):
        filename,suffix=QFileDialog.getOpenFileName(self,'选择绑定的音频文件','','*')
        if len(filename)==0:
            self.showInfoToUi(self.DEF_ui_showToProcess,'选择绑定的音频文件','你未进行操作')
            return

        i_dict={DEFINE.KEY_addTextLogo_fontcolor:self.ui.lineEdit_textLogo_fontColor.text(),
                DEFINE.KEY_addTextLogo_fontsize:self.ui.spinBox_textLogo_fontsize.value(),
                DEFINE.KEY_addTextLogo_text:self.ui.lineEdit_textLogo.text(),
                DEFINE.KEY_addTextLogo_linkaudio:filename
                }
        self.addTextLogo_linklist.append(i_dict)
        self.showInfoToUi(self.DEF_ui_showToProcess,'视频添加添加文字水印,已经添加:','{}'.format(self.addTextLogo_linklist))


    def slot_pushButton_addTextLogo_linkAudio_clearall(self):
        self.addTextLogo_linklist.clear()
        self.showInfoToUi(self.DEF_ui_showToProcess,'视频添加添加文字水印,已经清空','')

    #操作appkey 以后要更新下拉框
    #添加appkey
    def slot_addAppKey(self):
        appkey=self.ui.lineEdit_AppKey.text()
        appkeyname=self.ui.lineEdit_AppKey_name.text()
        if len(appkey)==0 :
            self.show_info('appkey未填写')
            return
        if len(appkeyname)==0:
            self.show_info(('appkeyname未填写'))
            return
        try:
            with open(DEFINE.DEF_IDINFO_PATH, 'r', encoding='utf-8') as rfile:
                text = rfile.read()
                if len(text) != 0:
                    infodict = eval(text)
                    if type(infodict) == type({}):
                        appkeylist = infodict[DEFINE.KEY_AppKey]
                        appkeylist.append({DEFINE.KEY_AppKey: appkey, DEFINE.KEY_AppKeyName: appkeyname})
                        infodict[DEFINE.KEY_AppKey] = appkeylist
                        with open(DEFINE.DEF_IDINFO_PATH, 'w', encoding='utf-8') as wfile:
                            wfile.write(str(infodict))
                else:
                    infodict = {
                        DEFINE.KEY_AccessKeyId: self.ui.lineEdit_AccessKeyId.text(),
                        DEFINE.KEY_AccessKeySecret: self.ui.lineEdit_AccessKeySecret.text(),
                        DEFINE.KEY_Endpoint: self.ui.lineEdit_Endpoint.text(),
                        DEFINE.KEY_BucketName: self.ui.lineEdit_BucketName.text(),
                        DEFINE.KEY_AppKey: [{DEFINE.KEY_AppKey: appkey, DEFINE.KEY_AppKeyName: appkeyname}]
                    }
                    with open(DEFINE.DEF_IDINFO_PATH, 'w', encoding='utf-8') as wfile:
                        wfile.write(str(infodict))
        except Exception:
            msg=traceback.format_exc()
            print(msg)
            self.show_info(msg)
        else:
            self.show_idInfo()
            self.show_info('保存成功')

    #查看已经添加的appkey
    def slot_showAppKey(self):
        with open(DEFINE.DEF_IDINFO_PATH, 'r', encoding='utf-8') as rfile:
            text=rfile.read()
            if len(text)!=0:
                infodict = eval(text)
                if type(infodict) == type({}):
                    appkeylist = infodict[DEFINE.KEY_AppKey]
                    self.ui.plainTextEdit_appkey_show.setPlainText(str(appkeylist))
                else:
                    self.show_info('保存的数据错误:jingting_datas/idInfo.json')

    #删除appkey
    def slot_delAppKey(self):
        appkey = self.ui.lineEdit_AppKey.text()
        appkeyname = self.ui.lineEdit_AppKey_name.text()
        if len(appkey) == 0:
            self.show_info('appkey未填写')
            return
        with open(DEFINE.DEF_IDINFO_PATH, 'r', encoding='utf-8') as rfile:
            text=rfile.read()
            if len(text)==0:
                return
            infodict = eval()
            if type(infodict) == type({}):
                # appkeylist=[]
                appkeylist = infodict[DEFINE.KEY_AppKey]
                bo_haveAppKey=False
                for i_dict in appkeylist:
                    if i_dict[DEFINE.KEY_AppKey]==appkey:
                        appkeylist.remove(i_dict)
                        infodict[DEFINE.KEY_AppKey]=appkeylist
                        with open(DEFINE.DEF_IDINFO_PATH, 'w', encoding='utf-8') as wfile:
                            wfile.write(str(infodict))
                        self.show_info('删除appkey成功')
                        self.show_idInfo()
                        bo_haveAppKey=True
                        break
                if bo_haveAppKey==False:
                    self.show_info('没有此条appkey,检查是否输入错误')
            else:
                self.show_info('保存的数据错误:jingting_datas/idInfo.json')

    #工具 字幕转换
    def slot_pushButton_tool_swapSubtit_choice(self):
        fileslist, suffix = QFileDialog.getOpenFileNames(self, '选择ass或者srt文件', '', '*')
        if len(fileslist) == 0:
            self.showInfoToUi(self.DEF_ui_showToProcess, '注意:', '你未选择文件,不进行操作')
        else:
            self.swapSubtitList = fileslist
            self.ui.plainTextEdit_tool_swapSubtit_showProcess.appendPlainText('已经导入字幕文件:\n{}'.format(fileslist))

    def slot_pushButton_tool_swapSubtit_start(self):
        if len(self.swapSubtitList)==0:
            self.ui.plainTextEdit_tool_swapSubtit_showProcess.appendPlainText('未选择文件')
            return
        lis=list(self.swapSubtitList)
        self.swapSubtitList.clear()
        self.ui.pushButton_tool_swapSubtit_start.setEnabled(False)
        for item in lis:
            name,suffix=os.path.splitext(item)
            if suffix not in ['.ass','.ssa','.srt']:
                self.ui.plainTextEdit_tool_swapSubtit_showProcess.appendPlainText('不可转换:{}'.format(item))
                continue
            if suffix in ['.ass','.ssa']:
                tar=name+'.srt'
            else:
                tar=name+'.ass'
            dic= tool.swapSubtit(item, tar)
            if dic[DEFINE.KEY_RETCODE]==0:
                self.ui.plainTextEdit_tool_swapSubtit_showProcess.appendPlainText('制作成功:{}\n'.format(item))
            else:
                self.ui.plainTextEdit_tool_swapSubtit_showProcess.appendPlainText('制作失败:{}\n{}\n'.format(item, dic[
                    DEFINE.KEY_OUTINFO]))
            time.sleep(1)
        self.ui.pushButton_tool_swapSubtit_start.setEnabled(True)

    #工具 翻译
    def tool_trans(self,text,dest):
        try:
            tr = Translator()
            t = tr.translate(text, dest=dest)
            if type(text)==type(list()):
                tran_text=''
                for item in t:
                    text=item.text.replace('|','\n')
                    tran_text+=text+'.'
            else:
                tran_text = t.text
            self.mainWindowSignal.tool_trans_over.emit(tran_text)
        except Exception:
            msg=traceback.format_exc()
            print(msg)
            self.mainWindowSignal.tool_trans_over.emit('翻译错误:\n'+msg)

    def slot_pushButton_tool_trans_satrt(self):
        text=self.ui.plainTextEdit_tool_trans_oriText.toPlainText()
        if len(text)==0:
            self.show_info('输入文本为空')
            return
        if self.ui.checkBox_subtitTrans_manLangue.isChecked():
            des = self.ui.lineEdit_subtitTrans_manLangueText.text()
        else:
            des = self.ui.comboBox_subtitTrans_langue.currentText()

        if len(text)<=4500:
            mythread = threading.Thread(target=self.tool_trans, args=(text,des))
        else:
            text=text.replace('。','.')
            text=text.replace('\n','|')
            lis=text.split('.')
            mythread = threading.Thread(target=self.tool_trans, args=(lis, des))
        # 设置守护线程,主线程UI结束,制作视频任务也结束
        mythread.daemon = True
        mythread.start()
        self.ui.plainTextEdit_tool_trans_tarText.setPlainText('正在翻译中...')

    def slot_trans_over(self,text):
        self.ui.plainTextEdit_tool_trans_tarText.setPlainText(text)
        # self.ui.plainTextEdit_tool_trans_oriText.setPlainText('翻译完成!')

    def slot_trans_showTextLen(self):
        le=len(self.ui.plainTextEdit_tool_trans_oriText.toPlainText())
        self.ui.lineEdit_tool_trans_showlen.setText('你已输入:\n{}字'.format(le))



#点击 开始制作
    def startMakeVideo(self):
        #判断信息是否完整
        if self.idinfo==None:
            self.showInfoToUi(self.DEF_ui_showToProgress,'错误:','阿里云账户信息不完整')
            return
        if self.ui.checkBox_makeVideo_firstPureCorlor.isChecked()==False and len(self.makeVideo_BacImg)==0:
            self.showInfoToUi(self.DEF_ui_showToProgress, '错误:', '你开启了图片作为背景,但是未选择图片文件')
            return
        if len(self.ui.lineEdit_saveVideoPath.text())==0 :
            self.showInfoToUi(self.DEF_ui_showToProgress,'错误:','未设置视频输出路径')
            return
        if (len(self.ui.lineEdit_saveVideoName.text())==0 and self.ui.checkBox_useAudNameAsVidName.isChecked()==False):
            self.showInfoToUi(self.DEF_ui_showToProgress, '错误:', '未设置输出视频的名称,并且未开启音频名称用作视频名称')
            return
        if len(self.audioFilelist)==0:
            self.showInfoToUi(self.DEF_ui_showToProgress,'错误:','未选择音频')
            return
        if len(self.ui.comboBox_chioce_appkey.currentText())==0:
            self.showInfoToUi(self.DEF_ui_showToProgress,'错误:','未选择AppKey')
            return

        #批量制作(顺序排列,单线程)
        try:
            #加入子线程
            mythread=threading.Thread(target=self.makeVideoSequentially,args=(list(self.audioFilelist),))
            #设置守护线程,主线程UI结束,制作视频任务也结束
            # mythread.setDaemon(True)
            mythread.daemon=True
            mythread.start()
            #清空
            self.audioFilelist.clear()
        except Exception as e:
            msg=traceback.format_exc()
            self.showInfoToUi(self.DEF_ui_showToProgress,'程序错误','')
            self.showInfoToUi(self.DEF_ui_showToProcess,'程序错误',msg)

    #开始制作-单个文件
    def startMakeVideo_singleFile(self,audiofile,callBackFun_process=None,is_ui_model=False):
        try:
            #回调函数
            def callback(process):
                print(process)
            if  callBackFun_process==None:
                callBackFun_process=callback
            # '''
            #压缩音频=============
            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('开始:'), '压缩音频')
            audio_compressfile='../jingting_tempFiles/Make_video_sequentially/{}'.format(os.path.basename(audiofile))
            res_dict= makeVideo.audio_compress(audiofile, audio_compressfile)
            # 制作结果信息
            if is_ui_model:
                self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProcess, '{}'.format('压缩音频的ffmpeg信息:'),
                                                       res_dict[DEFINE.KEY_OUTINFO])
            if res_dict[DEFINE.KEY_RETCODE] != 0:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('错误:'), '压缩音频时失败')
                return False
            else:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'), '压缩音频成功')

            callBackFun_process(1/8)

            # 将音频文件上传到阿里云oss,获取url===============
            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('开始:'), '将音频文件上传到阿里云oss')
            saveoss_audiofile_name = 'jingting_tempfiles/{}'.format(os.path.split(audiofile)[1])
            bo_success,audioUrl= ossutil.uploadAudioFilesToAlibabaCloud(audio_compressfile, saveoss_audiofile_name, self.idinfo.id, self.idinfo.secret, self.idinfo.endpoint, self.idinfo.bucketname, self.emitSignal_processPar)
            if not bo_success:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress,'{}'.format('错误:'),'上传音频文件到oss失败')
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProcess,'{}'.format('错误:上传音频文件到oss失败'),audioUrl)
                return False
            else:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'), '上传音频文件到oss')

            callBackFun_process(float(2/8))

            # 调用语音识别,得到识别后的文本===============
            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('开始:'), '调用语音识别')
            save_audioToText_file='../jingting_tempFiles/Make_video_sequentially/audioToText.txt'
            appkey=eval(self.ui.comboBox_chioce_appkey.currentText())[DEFINE.KEY_AppKey]
            if is_ui_model:
                bo_success,err_info= audioToText.fileTrans(self.idinfo.id, self.idinfo.secret, appkey, audioUrl, save_audioToText_file, self.ui.spinBox_subtit_max_single_segment_time.value(), self.emitSignal_TextInfo)
            else:
                bo_success,err_info= audioToText.fileTrans(self.idinfo.id, self.idinfo.secret, appkey, audioUrl, save_audioToText_file, self.ui.spinBox_subtit_max_single_segment_time.value())
            if not bo_success:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('错误:'), '语音识别失败')
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProcess, '{}'.format('错误:语音识别失败,具体错误,请对照 阿里云录音文件识别服务 的接口文档错误码'), err_info)
                return False
            else:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'), '语音识别成功')

            callBackFun_process(float(3/8))

            # 是否对字幕长度优化,得到 字幕开始,结束时间 及内容的字典列表==========
            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('开始:'), '获取字幕信息列表')
            ass_list=[]
            try:
                if self.ui.checkBox_subtit_fixlen.isChecked() ==True:
                    ass_list= textToAss.textToass_list('../jingting_tempFiles/Make_video_sequentially/audioToText.txt', self.ui.spinBox_subtit_fixTextLen.value(), self.ui.spinBox_subtit_fixlen_range_.value())
                else:
                    ass_list= textToAss.textToass_list('../jingting_tempFiles/Make_video_sequentially/audioToText.txt', 0, 0)
            except Exception as e:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('错误:'), '获取字幕信息列表失败')
                print(e)
                return False
            else:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'), '获取字幕信息列表成功')

            callBackFun_process(float(4/8))

            # 是否翻译==============
            if self.ui.checkBox_subtitTrans.isChecked():
                if self.ui.checkBox_subtitTrans_manLangue.isChecked():
                    targetLan=self.ui.lineEdit_subtitTrans_manLangueText.text()
                else:
                    targetLan=self.ui.comboBox_subtitTrans_langue.currentText()
                if len(targetLan)==0:
                    if is_ui_model:
                        self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('错误:'), '翻译失败,未选择目标语言')
                    return False
                self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('开始:'), '翻译')
                bo_success,trans_ass_list= mytranslate.translate(ass_list, True, targetLan)
                ass_list=trans_ass_list
                if not bo_success:
                    print(trans_ass_list)
                    if is_ui_model:
                        self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('错误:'), '翻译失败')
                        self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProcess,'错误:翻译失败',trans_ass_list)
                    return False
                else:
                    if is_ui_model:
                        self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'), '翻译成功')

            callBackFun_process(float(5/8))

            # 制作ass字幕============
            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('开始:'), '制作ass字幕')
            # -1 是粗体，0 不是。
            if self.ui.checkBox_subtit_bold.isChecked() :
                Bold=-1
            else:
                Bold=0
            if self.ui.checkBox_subtit_italic.isChecked():
                Italic=-1
            else:
                Italic=0
            if self.ui.checkBox_subtit_underline.isChecked():
                Underline=-1
            else:
                Underline=0
            if self.ui.checkBox_subtit_spacing.isChecked():
                Spacing=self.ui.spinBox_subtit_spacing.value()
            else:
                Spacing=''
            #十六进制颜色(#FFFFFF
            #字幕颜色(例如，&H00FFFFFF。&H+00+BBGGRR
            color=self.ui.lineEdit_subtit_primaryColour.text()
            newcolol=color.replace('#','')
            font_color = '&H00' + newcolol[4:7] + newcolol[2:4] + newcolol[0:2]
            arg_dict={DEFINE.KEY_assStyle_Fontname:self.ui.fontComboBox_subtit_font.currentText(),
                      DEFINE.KEY_assStyle_Fontsize:self.ui.spinBox_subtit_fontSize.value(),
                      DEFINE.KEY_assStyle_PrimaryColour:font_color,
                      DEFINE.KEY_assStyle_Bold:Bold,
                      DEFINE.KEY_assStyle_Italic:Italic,
                      DEFINE.KEY_assStyle_Underline:Underline,
                      DEFINE.KEY_assStyle_Spacing:Spacing,
                      DEFINE.KEY_assStyle_Alignment:self.ui.spinBox_subtit_alignment.value()}
            videosubtitfile='../jingting_tempFiles/Make_video_sequentially/videoSubtitle.ass'
            try:
                textToAss.textToass_file(ass_list, videosubtitfile, arg_dict, MarginV=12)
            except:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('错误:'), '制作ass字幕失败')
                return False
            else:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'), '制作ass字幕成功')

            # ass文件=========
            if self.ui.checkBox_MakeModel_Assfile.isChecked():
               try:
                   audioname, suffix = os.path.splitext(os.path.basename(audiofile))
                   subtitfile = '{0}/{1}.ass'.format(DEFINE.DEF_ASSFILE_PATH, audioname)
                   with open(videosubtitfile,'r',encoding='utf-8') as rfile:
                       t=rfile.read()
                       with open(subtitfile,'w',encoding='utf-8') as  wfile:
                           wfile.write(t)
               except Exception:
                   msg=traceback.format_exc()
                   print(msg)
                   self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress,'错误:','复制ass字幕失败')

            #纯文本===========
            if self.ui.checkBox_MakeModel_word.isChecked():
                try:
                    textlist=[]
                    for item in ass_list:
                        textlist.append(item[DEFINE.KEY_TEXT] + '\n')
                    text=''.join(textlist)
                    text=text.replace('\\N','\n')
                    audioname, suffix = os.path.splitext(os.path.basename(audiofile))
                    wordfile = '{0}/{1}.doc'.format(DEFINE.DEF_WORDFILE_PATH, audioname)
                    with open(wordfile,'w+',encoding='utf-8') as wfile:
                        wfile.write(text)
                except Exception:
                    msg = traceback.format_exc()
                    print(msg)
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '错误:', '生成纯文本失败')

            callBackFun_process(float(6 / 8))

            # 制作视频=========
            if self.ui.checkBox_MakeModel_Video.isChecked():
                # 水印**********
                text = '';
                color = '';
                size = 0
                if len(self.addTextLogo_linklist) != 0:
                    info_dict = {}
                    for i_dict in self.addTextLogo_linklist:
                        file = i_dict[DEFINE.KEY_addTextLogo_linkaudio]
                        if file == audiofile:
                            info_dict = i_dict
                            break
                    if len(info_dict) != 0:
                        # 添加
                        text = info_dict[DEFINE.KEY_addTextLogo_text]
                        color = info_dict[DEFINE.KEY_addTextLogo_fontcolor]
                        size = info_dict[DEFINE.KEY_addTextLogo_fontsize]

                #制作选项字幕********
                bo_make_OptionSubtit=False
                OptionSubtitfilename='../jingting_tempFiles/Make_video_sequentially/OptionSubtit.ass'
                if len(self.addOptionSubtit_linklist)!=0:
                    infodict={}
                    for i_dict in self.addOptionSubtit_linklist:
                        linkaudio=i_dict[DEFINE.KEY_addOptionSubtit_linkaudio]
                        if linkaudio==audiofile:
                            infodict=i_dict
                            break
                    if len(infodict)!=0:
                        self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('开始:'), '制作选项字幕')
                        #判断四六级字幕 还是 通用字幕
                        if infodict[DEFINE.KEY_addOptionSubtit_model]== DEFINE.DEF_addOptionSubtit_eng46_model:
                            bo_success,e= tool.English_4_and_6_options_subtitle_production(infodict[
                                                                                               DEFINE.KEY_addOptionSubtit_text]
                                                                                           , save_audioToText_file
                                                                                           , infodict[
                                                                                               DEFINE.KEY_addOptionSubtit_sytle]
                                                                                           , OptionSubtitfilename)
                        # 视频添加通用选项字幕
                        elif infodict[DEFINE.KEY_addOptionSubtit_model]== DEFINE.DEF_addOptionSubtit_general_model:
                            lis = infodict[DEFINE.KEY_addOptionSubtit_text]
                            if len(lis)==0:
                                bo_success=False
                                e='选项字幕制作失败:infodict[DEFINE.KEY_addOptionSubtit_text]长度为零'
                            else:
                                bo_success,e= textToAss.textToass_file(lis, OptionSubtitfilename, infodict[
                                    DEFINE.KEY_addOptionSubtit_sytle])

                        if not bo_success:
                            if is_ui_model:
                                self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('错误:'),
                                                                       '选项字幕制作失败,不进行添加')
                                self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProcess,'选项字幕制作失败:',e)
                            bo_make_OptionSubtit= False
                        else:
                            if is_ui_model:
                                self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'),
                                                                  '选项字幕制作成功')
                            bo_make_OptionSubtit=True
                # '''
                # OptionSubtitfilename='../jingting_tempFiles/Make_video_sequentially/OptionSubtit.ass'
                # videosubtitfile='../jingting_tempFiles/Make_video_sequentially/videoSubtitle.ass'

                # 制作视频**********
                self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('开始:'), '制作视频')
                    #参数
                width=self.ui.spinBox_makeVideo_width.value()
                heigth=self.ui.spinBox_makeVideo_height.value()
                frameRate=self.ui.spinBox_makeVideo_frameRate.value()
                    #使用对应音频文件的名称作为输出视频的名称
                    #windows 路径是 \ 号 拼接时注意
                if self.ui.checkBox_useAudNameAsVidName.isChecked():
                    # 当前音频文件的名称,无后缀
                    name, extension = os.path.splitext(os.path.basename(audiofile))
                    save_videofile=self.saveVideoPath+'\\'+name+self.ui.comboBox_saveVieo_suffix.currentText()
                else:
                    name=self.ui.lineEdit_saveVideoName.text()
                    save_videofile = self.saveVideoPath+'\\'+name+'{}'.format(datetime.datetime.now().strftime('%H时%M分'))+self.ui.comboBox_saveVieo_suffix.currentText()
                    #背景图
                picFile=self.makeVideo_BacImg
                    #视频时长(整数 或者 str字符:格式(00:00:00.00))
                # total_video_time=textToAss.get_asslist_lastTime(ass_list)
                # total_video_time=60
                bo_success,total_video_time= makeVideo.getVideoTime(audiofile)#获取音频文件时长,格式(00:00:00.00)
                if not bo_success:
                    if is_ui_model:
                        self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('错误:'), '制作视频时,获取时长失败')
                    return False
                #字幕列表
                subtit_list=[]
                subtit_list.append(videosubtitfile)
                # subtit_list.append(OptionSubtitfilename)
                if bo_make_OptionSubtit==True:
                    subtit_list.append(OptionSubtitfilename)

                #开始制作 纯色or图片 视频
                if self.ui.checkBox_makeVideo_firstPureCorlor.isChecked():
                    #简单制作纯图视频
                    # res_dict=makeVideo.make_blank_video(save_videofile,total_video_time,self.ui.lineEdit_makeVideo_pureColour.text(),width,heigth,frameRate)
                    #可以混合音频,多字幕,水印
                    res_dict= makeVideo.make_blank_video_formAll(save_videofile, total_video_time, self.ui.lineEdit_makeVideo_pureColour.text(), audiofile, subtit_list, text, size, color, width, heigth, frameRate)
                    if is_ui_model:
                        self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProcess, '{}'.format('生成视频的ffmpeg信息:'), res_dict[
                            DEFINE.KEY_OUTINFO])
                    if res_dict[DEFINE.KEY_RETCODE] != 0 :
                        if is_ui_model:
                            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('错误:'), '生成视频时失败')
                        return False
                    else:
                        if is_ui_model:
                            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'), '生成视频成功')
                else:
                    # 图片背景视频分辨率
                    if self.ui.radioButton_makeVideo_usePicWidHei.isChecked()==False:
                        if self.ui.radioButton_makeVideo_useComWid.isChecked():
                            heigth=0
                        elif self.ui.radioButton_makeVideo_useComHei.isChecked():
                            width=0
                    elif self.ui.radioButton_makeVideo_usePicWidHei.isChecked()==True:
                        width=0;heigth=0
                    # 简单制作纯图视频
                    # res_dict=makeVideo.make_pic_video(picFile,total_video_time,save_videofile,0,0,Framerate=frameRate)
                    #可以混合音频,多字幕,水印
                    res_dict= makeVideo.make_pic_video_formAll(picFile, total_video_time, audiofile, subtit_list, text, size, color, save_videofile, width, heigth, frameRate)
                    #制作结果信息
                    if is_ui_model:
                        self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProcess, '{}'.format('生成视频的ffmpeg信息:'), res_dict[
                            DEFINE.KEY_OUTINFO])
                    if res_dict[DEFINE.KEY_RETCODE] != 0 :
                        if is_ui_model:
                            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('错误:'), '生成视频时失败')
                        return False
                    else:
                        if is_ui_model:
                            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'), '生成视频成功')

            callBackFun_process(float(7/8))

            # 善后处理,删除不需要的文件==========
            os.remove(audio_compressfile)
            # oss文件
            bo_success, e = ossutil.deleteFileFromAlibabaCloud(self.idinfo.id, self.idinfo.secret,
                                                               self.idinfo.endpoint, self.idinfo.bucketname,
                                                               saveoss_audiofile_name)
            if bo_success:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'),
                                                           '删除oss临时文件成功')
                else:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('失败:'),
                                                           '删除oss临时文件失败')

            callBackFun_process(float(8 / 8))
        except Exception:
            # 善后处理,删除不需要的文件==========
            os.remove(audio_compressfile)
            # oss文件
            bo_success, e = ossutil.deleteFileFromAlibabaCloud(self.idinfo.id, self.idinfo.secret,
                                                               self.idinfo.endpoint, self.idinfo.bucketname,
                                                               saveoss_audiofile_name)
            if bo_success:
                if is_ui_model:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('成功:'),
                                                           '删除oss临时文件成功')
                else:
                    self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('失败:'),
                                                           '删除oss临时文件失败')

            msg = traceback.format_exc()
            print(msg)
            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '错误:', '制作{}时出错'.format(audiofile))
            self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProcess, '错误:', msg)
            return False
        else:
            # 制作成功
            if is_ui_model:
                self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '{}'.format('制作成功'),'')

    # 批量制作(顺序排列, 单线程,子线程中,操作UI要通过信号)
    def makeVideoSequentially(self,audiofile_list):
        #开始按钮关闭
        self.mainWindowSignal.ui_pushButton_startMakeVideo.emit(False)
        #开始时间
        begin_task_time=time.perf_counter()
        id=datetime.datetime.now().strftime('%H时%M分')
        self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress, '本次任务开始(ID:{})'.format(id), '')
        while True:
            if len(audiofile_list)==0:
                end_task_time=time.perf_counter()
                self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress,'本次任务结束(ID:{})'.format(id),'用时:{:.2f}分钟'.format((end_task_time-begin_task_time)/60))
                self.mainWindowSignal.ui_pushButton_startMakeVideo.emit(True)
                break
            else:
                audiofile=audiofile_list[0]
                #单个制作
                bo_success=self.startMakeVideo_singleFile(audiofile,self.emitSignal_progressPar,True)
                if bo_success==False:
                    self.mainWindowSignal.ui_pushButton_startMakeVideo.emit(True)
                    break
                #间隔时间
                time.sleep(5)
                #列表中删除已经完成的音频
                del audiofile_list[0]
                self.mainWindowSignal.ui_textInfo.emit(self.DEF_ui_showToProgress,'\n\n本次任务(ID:{}) 还未制作的音频数:{}\n'.format(id,len(audiofile_list)),'')


# 程序入口
if __name__ == '__main__':
    # 创建app
    app = QApplication([])
    # 实例化主窗口
    window = mainWindow()
    window.show()
    # 事件循环
    app.exec_()
